#include "FloorSpikes.h"

// Access
#include "GamePlayState.h"

// Constructor
FloorSpikes::FloorSpikes(void) : JustRaised(false), SpikesUp(false), CooldownTimer(3.0f)
{ 
	// Set the hazard type
	HzType = HZ_SPIKES;

	// Set the part of the image to use
	image.top = 0;
	image.bottom = 32;
	image.left = 64;
	image.right = 96;

	SetWidth(32);
	SetHeight(32);
}

// Destructor
FloorSpikes::~FloorSpikes(void) { }

// Draw
void FloorSpikes::Render(void)
{
	// Get the camera
	int camx = GamePlayState::GetInstance()->GetCamX();
	int camy = GamePlayState::GetInstance()->GetCamY();

	// Don't draw if it's off screen
	if( GetX() < camx || GetY() < camy || GetX() > camx + 800 || GetY() > camy + 600)
		return;

	// Do the basic rendering
	Hazard::Render();
}

// Update
void FloorSpikes::Update(float elapsedTime)
{
	// Get the camera
	int camx = GamePlayState::GetInstance()->GetCamX();
	int camy = GamePlayState::GetInstance()->GetCamY();

	// Don't update if it isn't onscreen
	if( GetX() < camx || GetY() < camy || GetX() > camx + 800 || GetY() > camy + 600 )
		return;

	JustRaised = false;

	// Flip the states based on the cooldown
	CooldownTimer -= elapsedTime;
	if( CooldownTimer <= 0 )
	{
		SpikesUp = !SpikesUp;
		if( SpikesUp ) JustRaised = true;
		CooldownTimer = 3.0f;

		if( SpikesUp )
			image.right = 32 + (image.left = 96);
		else
			image.right = 32 + (image.left = 64);

	}

	// Lower the health of things colliding with it
	for(unsigned int i = 0; i < Collisions.size(); ++i)
	{
		if( Collisions[i]->GetType() == OBJ_PLAYER )
		{
			((Player*)Collisions[i])->TakeDam(10*elapsedTime);
			// Bonus damage if the spikes just raised
			if( JustRaised ) ((Player*)Collisions[i])->TakeDam(20);
		}
		if( Collisions[i]->GetType() == OBJ_ENEMY )
		{
			Enemy* e = (Enemy*)(Collisions[i]);
			e->SetHealth(e->GetHealth() - 10*elapsedTime);
			// Bonus damage
			if( JustRaised ) e->SetHealth(e->GetHealth() - 20);
		}
		Collisions[i]->Release();
	}

	// Clear out the list of collisions
	Collisions.clear();
}

// Collision response
bool FloorSpikes::CheckCollision(IEntity* base)
{
	// Do damage to bots that touch the spikes
	if( Entity::CheckCollision(base) )
	{
		if( base->GetType() == OBJ_PLAYER || base->GetType() == OBJ_ENEMY )
		{
			Collisions.push_back((Entity*)base);
			((Entity*)(base))->AddRef();
			return true;
		}
		return false;
	}
	return false;
}